package com.study.http_study;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * @author liuguibin
 * @date 2020-12-27 21:22
 * HttpURLConnection是Java的标准类，它继承自URLConnection，可用于向指定网站发送GET请求、POST请求
 */
public class HttpURLConnectionUtils {
    protected static final Logger logger = LoggerFactory.getLogger(HttpURLConnectionUtils.class);

    //https://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=15962598574
    public static String getData(String url) {
        String msg = "";
        try {
            // 1. 得到访问地址的URL
            URL url1 = new URL(url);
            // 2. 得到网络访问对象java.net.HttpURLConnection
            HttpURLConnection connection = (HttpURLConnection) url1.openConnection();
            // 设置是否向HttpURLConnection输出
            connection.setDoOutput(false);
            // 设置是否从httpUrlConnection读入
            connection.setDoInput(true);
            // 设置请求方式
            connection.setRequestMethod("GET");
            // 设置是否使用缓存
            connection.setUseCaches(true);
            // 设置此 HttpURLConnection 实例是否应该自动执行 HTTP 重定向
            connection.setInstanceFollowRedirects(true);
            // 设置超时时间
            connection.setConnectTimeout(3000);
            // 3.连接
            connection.connect();
            // 4. 得到响应状态码的返回值 responseCode,200
            int status = connection.getResponseCode();
            //5. 如果返回值正常，数据在网络中是以流的形式得到服务端返回的数据
            if (status == HttpURLConnection.HTTP_OK) {
                // 从流中读取响应信息
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "gbk"));
                String line = null;
                // 循环从流中读取
                while ((line = reader.readLine()) != null) {
                    msg += line + "\n";
                }
                reader.close();
            }
            // 6. 断开连接，释放资源
            connection.disconnect();
        } catch (MalformedURLException e) {
            logger.info("url错误");
        } catch (IOException e) {
            logger.info("url连接出错");
        }
        return msg;
    }

    /**
     * 设置密码
     * @param url
     * @param params
     * @return
     */
    public static String postData(String url, String params) {
        String msg = "";
        try {
            URL url1 = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) url1.openConnection();
            connection.setRequestMethod("POST");
            connection.setConnectTimeout(3000);
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            // 设置使用标准编码格式编码参数的名-值对
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.connect();
            //String params = "username=test&password=123456";
            OutputStream out = connection.getOutputStream();
            out.write(params.getBytes());

            out.flush();
            out.close();
            int status = connection.getResponseCode();
            if (status == HttpURLConnection.HTTP_OK) {
                // 从流中读取响应信息
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf8"));
                String line = null;
                // 循环从流中读取
                while ((line = reader.readLine()) != null) {
                    msg += line + "\n";
                }
                reader.close();
            }
            // 6. 断开连接，释放资源
            connection.disconnect();


        } catch (MalformedURLException e) {
            logger.info("url错误");
        } catch (IOException e) {
            logger.info("url连接出错");
        }
        return msg;
    }
}
